package com.qf.ssm.service.impl;

import com.qf.ssm.pojo.BaseUser;
import com.qf.ssm.pojo.User;
import com.qf.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Service
@Transactional
public class MyUserDetailsService implements UserDetailsService {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户的数据
        User user = userService.findUserByName(username);
        if(user==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        if(user.getStatus().equals("0")){
            throw new DisabledException("用户被禁用");
        }
        //将我们查询到的密码返回，spring 就会自动帮我们判断是不是,如果比较一致,就会执行我们的自定义的 successhandler
        BaseUser baseUser = new BaseUser(username, user.getPassword(), new ArrayList<>());
        baseUser.setUid(user.getId());
        return baseUser;
    }
}
